package com.situ.company.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public final class FmtUpload {

	public final static String FILE_NAMES = "filenames";
	/**
	 * 实现服务器端保存上传多张图片的功能
	 * @param req
	 * @return Map key=非文件域参数名 value=非文件域参数值（key=filenames values=保存图片文件名集合）
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public static Map<String, Object> upload(HttpServletRequest req) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(req);
		Map<String,Object> result = new HashMap<>();
		List<String> names = new ArrayList<>();
		for(FileItem item: items) {
			if(item.isFormField()) {//是否是非文件域参数
				String name = item.getFieldName();
				//System.out.println("name="+name);
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
				//System.out.println("value="+value);
				result.put(name, value);
			}else {//文件域表单元素--保存文件   
				//System.out.println(item.getFieldName()+""+item.getName());
				String fn =  item.getName();
				FileOutputStream fos = new FileOutputStream(getFPath()+"/"+fn);
				InputStream is = item.getInputStream();
				int length = -1;
				byte[] b= new byte[1024*1024];
				while(-1 !=(length = is.read(b)))
					fos.write(b,0,length);
				fos.flush();
				fos.close();
				is.close();
				names.add(fn);
				
			}
		}
		result.put(FILE_NAMES,names);
		return result;
	}
	
	public static String getFName(FileItem item) {//获得唯一的文件名加上上传文件的扩展名
		String fn = item.getName();
		return fn=UUID.randomUUID().toString()+fn.substring(fn.indexOf("."));
		
	}
	  
	
	
	public static File getFPath() {//保存上传来的文件的目录
		File f = new File("D:\\思途视频");//目录
		if(!f.exists()) {
			f.mkdir();
		}
			
		return f;
		
	}
	
	public static void delFile(String filename) {
		File f = new File(getFPath()+"/"+filename);
		f.delete();
	}
}
